<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">

      <el-input v-model="listQuery.userId" clearable class="filter-item" style="width: 200px;" placeholder="會員Id" />
      <el-input v-model="listQuery.mobile" clearable class="filter-item" style="width: 200px;" placeholder="手機號" />

      <!-- <el-select v-model="listQuery.virtualIs" clearable style="width: 200px" class="filter-item" placeholder="用户类型">
        <el-option v-for="(key, value) in userType" :key="key" :label="key" :value="value" />
      </el-select> -->

      <el-select v-model="listQuery.post" clearable style="width: 200px" class="filter-item" placeholder="職位">
        <el-option v-for="(key, value) in userLevel" :key="key" :label="key" :value="value +1" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
    <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="checkall">查看公司组织架构</el-button> 
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" width="100px" label="會員ID" prop="id" sortable />

      <el-table-column align="center" label="會員姓名">

        <template slot-scope="scope">
          <el-tag>{{ scope.row.surname }}{{ scope.row.username }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="會員號" prop="mobile" >
        <template slot-scope="scope">
          {{ scope.row.mobile | invitedCodes}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="職位" prop="userLevel">
        <template slot-scope="scope">
          <el-tag>{{ userLevel[scope.row.post -1] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="上級會員ID" prop="parentId" >
        <template slot-scope="scope">
          <el-tag :class="scope.row.parentId?'':'red'">{{ scope.row.parentId?scope.row.parentId:'没有上级' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="上級會員姓名" >
        <template slot-scope="scope">
          <el-tag :class="scope.row.parentId?'':'red'">{{ scope.row.parentId?(scope.row.psurname+scope.row.pusername):'没有上级' }} </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="上級推荐码" prop="pmobile">
        <template slot-scope="scope">
          <el-tag :class="scope.row.parentId?'':'red'">{{  scope.row.parentId?scope.row.pmobile:'没有上级'  | invitedCodes }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="本月pv值" prop="monthPv" >
        <template slot-scope="scope">
          {{ scope.row.monthPv?scope.row.monthPv:0 }}
        </template>
    </el-table-column>
      <el-table-column align="center" label="上月pv值" prop="lasMonthPv" >
        <template slot-scope="scope">
         {{scope.row.lasMonthPv?scope.row.lasMonthPv:0 }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="纍計pv值" prop="pvTotal" />

      <!-- <el-table-column align="center" label="性别" prop="gender">
        <template slot-scope="scope">
          <el-tag >{{ genderDic[scope.row.gender] }}</el-tag>
        </template>
      </el-table-column> -->

      <!-- <el-table-column align="center" label="生日" prop="birthday"/> -->

      <!-- <el-table-column align="center" label="用户等级" prop="userLevel">
        <template slot-scope="scope">
          <el-tag >{{ levelDic[scope.row.userLevel] }}</el-tag>
        </template>
      </el-table-column> -->

      <!-- <el-table-column align="center" label="注册时间" prop="addTime" sortable/>

      <el-table-column align="center" label="注册时长/天" prop="registTime" sortable/>

       -->

      <!-- <el-table-column align="center" label="状态" prop="status">
        <template slot-scope="scope">
          <el-tag>{{ statusDic[scope.row.status] }}</el-tag>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button type="primary" size="mini" @click="handleDetail(scope.row)">详情</el-button>
          <el-button type="warning" size="mini" @click="userAddress(scope.row)">地址</el-button>
          <el-button type="success" size="mini" @click="userCollection(scope.row)">收藏</el-button> -->
          <el-button type="success" size="mini" @click="groupOrg(scope.row)">組織架構</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 用户地址 -->
    <el-dialog :visible.sync="userAddressVisible" title="用户地址">
      <el-table :data="addressList" element-loading-text="正在查询中。。。" border fit highlight-current-row>
        <el-table-column align="center" label="收货人" prop="name" />
        <el-table-column align="center" label="省市" prop="province" />
        <el-table-column align="center" label="市" prop="city" />
        <el-table-column align="center" label="区" prop="county" />
        <el-table-column align="center" label="地址详情" prop="addressDetail" />
        <el-table-column align="center" label="手机号码" prop="tel" />
      </el-table>
    </el-dialog>

    <!-- 用户收藏 -->
    <el-dialog :visible.sync="userCollectionVisible" title="用户收藏">
      <el-table :data="collectionList" element-loading-text="正在查询中。。。" border fit highlight-current-row>
        <el-table-column align="center" property="iconUrl" label="圖片">
          <template slot-scope="scope">
            <img :src="scope.row.imgUrl" width="40">
          </template>
        </el-table-column>
        <el-table-column align="center" label="价格" prop="price" />
        <el-table-column align="center" label="库存" prop="num" />
        <el-table-column align="center" label="添加时间" prop="addTime" />
      </el-table>
    </el-dialog>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!-- 用户编辑对话框 -->
    <el-dialog :visible.sync="userDialogVisible" :title="isAdd==0?'用户编辑':'新增會員'">
      <el-form ref="userDetail" :model="userDetail" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        
        <el-form-item v-if="isAdd==0" label="用户名" prop="username">
          <el-input v-model="userDetail.username" :disabled="true" />
        </el-form-item>
        <el-form-item v-if="isAdd==1" label="用户名" prop="username">
          <el-input v-model="userDetail.username" />
        </el-form-item>

        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="userDetail.nickname" />
        </el-form-item>
        <!--        <el-form-item label="用户密码" prop="mobile">-->
        <!--          <el-input v-model="userDetail.password" />-->
        <!--        </el-form-item>-->
        <!-- <el-form-item label="出生日期" prop="birthday">
          <el-input v-model="userDetail.birthday" />
        </el-form-item> -->
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker v-model="userDetail.birthday" type="datetime" placeholder="选择日期" format="MM-dd" value-format="yyyy-MM-dd" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="上级id" prop="parentId">
          <el-input v-model="userDetail.parentId" type="number" />
        </el-form-item>
        <el-form-item label="邀请码" prop="inviteCode">
          <el-input v-model="userDetail.inviteCode" />
        </el-form-item>
        <el-form-item label="职位" prop="post">
          <!--          <el-input v-model="userDetail.post" />-->
          <el-select v-model="userDetail.post" placeholder="请选择"><el-option v-for="(item, index) in userLevel1" :key="index" :label="item" :value="index" /></el-select>
        </el-form-item>
        <el-form-item v-if="isAdd==0" label="个人/组织pv" prop="pvOne">
          <el-input v-model="userDetail.pvOne" />
        </el-form-item>
        <el-form-item label="是否接受推广信息" prop="acceptIs">
          <el-select v-model="userDetail.acceptIs" placeholder="请选择"><el-option v-for="(item, index) in AcceptDic" :key="index" :label="item" :value="index" /></el-select>
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="userDetail.email" />
        </el-form-item>

        <el-form-item label="用户手机" prop="mobile">
          <el-input v-model="userDetail.mobile" />
        </el-form-item>
        <el-form-item label="用户性别" prop="gender">
          <el-select v-model="userDetail.gender" placeholder="请选择"><el-option v-for="(item, index) in genderDic" :key="index" :label="item" :value="index" /></el-select>
        </el-form-item>
        <el-form-item label="用户等级" prop="userLevel">
          <el-select v-model="userDetail.userLevel" placeholder="请选择"><el-option v-for="(item, index) in levelDic" :key="index" :label="item" :value="index" /></el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="userDetail.status" placeholder="请选择"><el-option v-for="(item, index) in statusDic" :key="index" :label="item" :value="index" /></el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUserUpdate">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {findOrders,findOrders2,getMonthPv,getMonthPv2} from '@/api/pv'
import { fetchList2, userDetail, updateUser,findZzjg, addUser, userlistDao, getUserAddress, getUserCollection,getAllMonth ,getAllTotal,getAllLast} from '@/api/user'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
export default {
  name: 'User',
  components: { Pagination },
  data() {
    return {
      list: null,
      addressList: null,
      collectionList: null,
      list1: null,
      total: 0,
      listLoading: true,
      listQuery2:{},
      listQuery: {
        page: 1,
        limit: 20,
        username: undefined,
        mobile: undefined,
        userId: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      downloadLoading: false,
      genderDic: ['未知', '男', '女'],
      levelDic: ['普通用户', 'VIP用户', '高级VIP用户'],
      userLevel: ['普通会员', '经销商', '副总监', '总监', '区域总监','高级区域总监', '亚洲总监', '亚太区总监', '环球总监'],
      userType: ['注册会员', '游客'],
      statusDic: ['可用', '禁用', '注销'],
      AcceptDic: ['不接受', '接受'],
      userLevel1: ['请选择', '普通会员', '经销商', '副总监', '总监', '区域总监','高级区域总监', '亚洲总监', '亚太区总监', '环球总监'],
      userDialogVisible: false,
      userAddressVisible: false,
      userCollectionVisible: false,
      userDetail: {
      },
      isAdd: 1
    }
  },
  created() {
    this.getList()
  },
  filters:{
    invitedCodes(data){
      if(data=='没有上级'){
        return '没有上级'
      }
      let lackLength=0
      if(data && data.length<12){
        lackLength=12-data.length
      }
      let get0=''
      for (let index = 0; index < lackLength; index++) {
        get0+='0'
        
      }
      return get0+data
    }
  },
  methods: {
    invitedCodes2(data){
      let lackLength=0
      if(data.length<12){
        lackLength=12-data.length
      }
      let get0=''
      for (let index = 0; index < lackLength; index++) {
        get0+='0'
        
      }
      return get0+data
    },
    checkall(){
      const routerData = this.$router.resolve({
        path: '/tree',
        query: {
          type: 'all'
        }
      })
      window.open(routerData.href, '_blank')
    },
    addmember() {
      this.isAdd = 1
      // this.userDetail = row
      this.userDialogVisible = true
    },
    groupOrg(row) {
      const routerData = this.$router.resolve({
        path: '/tree',
        query: {
          userId: row.id
        }
      })
      window.open(routerData.href, '_blank')
    },
    async getList() {
      this.listLoading = true
      let response3=await getAllMonth({})
      let response4=await getAllTotal({})
      let response5=await getAllLast({})
      if (this.listQuery.userId) {
        this.listQuery.id=this.listQuery.userId
        fetchList2(this.listQuery).then(response => {
          this.list = []
          if (response.data.data) {
            let list=response.data.data.list
            for (let index = 0; index < list.length; index++) {
                const element = list[index];
                element['monthPv']=0
                element['pvTotal']=0
                element['lasMonthPv']=0
                for (let i = 0; i < response3.data.length; i++) {
                  const element2 = response3.data[i];
                  if(element.id == element2.user_id){
                    element['monthPv']+=Number(element2.integral_price)
                  }
                }
                for (let i = 0; i < response4.data.length; i++) {
                  const element3 = response4.data[i];
                  if(element.id == element3.user_id){
                    element['pvTotal']+=Number(element3.integral_price)
                  }
                }
                for (let i = 0; i < response5.data.length; i++) {
                  const element4 = response5.data[i];
                  if(element.id == element4.user_id){
                    element['lasMonthPv']+=Number(element4.integral_price)
                  }
                }
            }
            this.list=list
            this.total = 1
            this.listLoading = false
          } else {
            this.list = []
            this.total = 0
            this.listLoading = false
          }
        }).catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      } else {
        delete this.listQuery.id

        fetchList2(this.listQuery).then(response => {
            this.list = []
          let list=response.data.data.list
            for (let index = 0; index < list.length; index++) {
                const element = list[index];
                let pvTotal=0
                element['monthPv']=0
                element['pvTotal']=0
                element['lasMonthPv']=0
                for (let i = 0; i < response3.data.length; i++) {
                  const element2 = response3.data[i];
                  if(element.id == element2.user_id){
                    element['monthPv']+=Number(element2.integral_price)
                  }
                }
                for (let i = 0; i < response4.data.length; i++) {
                  const element3 = response4.data[i];
                  if(element.id == element3.user_id){
                    element['pvTotal']+=Number(element3.integral_price)
                  }
                }
                for (let i = 0; i < response5.data.length; i++) {
                  const element4 = response5.data[i];
                  if(element.id == element4.user_id){
                    element['lasMonthPv']+=Number(element4.integral_price)
                  }
                }
                
            }
          this.list=list
          this.total = response.data.data.total
          this.listLoading = false
        }).catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    async handleDownload() {
        this.listQuery2=Object.assign({},this.listQuery)
      this.listQuery2.limit=99999
      this.downloadLoading =true
      let response3=await getAllMonth({})
      let response4=await getAllTotal({})
      let response5=await getAllLast({})
        fetchList2(this.listQuery2).then(async response => {
          this.list1 = response.data.data.list
          for (let index = 0; index < this.list1.length; index++) {
            const element = this.list1[index];
            element['parentName']=element.psurname+element.pusername || ''
            element['parentId']=element.parentId?element.parentId:''
            element['sun']=element.surname+element.username
            if(element.mobile.length==8){
              element.mobile && (element['mobile']="0000"+element.mobile)
              element.pmobile && (element['pmobile']="0000"+element.pmobile)
            }else if(element.mobile.length==9){
              element.mobile && (element['mobile']="000"+element.mobile)
              element.pmobile && (element['pmobile']="000"+element.pmobile)
            }else if (element.mobile.length==10){
              element.mobile && (element['mobile']="00"+element.mobile)
              element.pmobile && (element['pmobile']="00"+element.pmobile)
            }else if (element.mobile.length==11){
              element.mobile && (element['mobile']="0"+element.mobile)
              element.pmobile && (element['pmobile']="0"+element.pmobile)
            }
            

            element['monthPv']=0
            element['pvTotal']=0
            element['lasMonthPv']=0
            for (let i = 0; i < response3.data.length; i++) {
              const element2 = response3.data[i];
              if(element.id == element2.user_id){
                element['monthPv']+=Number(element2.integral_price)
              }
            }
            for (let i = 0; i < response4.data.length; i++) {
              const element3 = response4.data[i];
              if(element.id == element3.user_id){
                element['pvTotal']+=Number(element3.integral_price)
              }
            }
            for (let i = 0; i < response5.data.length; i++) {
                const element4 = response5.data[i];
                if(element.id == element4.user_id){
                element['lasMonthPv']+=Number(element4.integral_price)
                }
            }

          }
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = ['會員Id', '會員姓名', '會員號', '職位', '上級會員ID', '上級會員姓名', '上級會員賬號', '本月PV值', '上月PV值', '纍計PV值']
            const filterVal = ['id', 'sun', 'mobile', 'postname', 'parentId', 'parentName', 'pmobile', 'monthPv', 'lasMonthPv', 'pvTotal']
            excel.export_json_to_excel2(tHeader, this.list1, filterVal, '用户信息')
            this.downloadLoading = false
          })


          
        }).catch(() => {
          this.list1 = []
          this.downloadLoading = false
        })
    },
    handleDetail(row) {
      this.isAdd = 0
      this.userDetail = row
      this.userDialogVisible = true
    },
    handleUserUpdate() {
      
      if (this.isAdd == 0) {
        
        updateUser(this.userDetail)
          .then((response) => {
            this.userDialogVisible = false
            this.$notify.success({
              title: '成功',
              message: '更新用户成功'
            })
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      } else {
        this.userDetail.parentId=Number(this.userDetail.parentId)
        addUser(this.userDetail)
          .then((response) => {
            if (response.data.errno == 0) {
              this.userDialogVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新用户成功'
              })
            } else {
              this.$notify.error({
                title: '添加失敗，可能是用戶名重複',
                message: response.data.errmsg
              })
            }
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }
    },
    userAddress(row) {
      getUserAddress(row.id)
        .then((response) => {
          this.addressList = response.data.data
          this.userAddressVisible = true
        })
    },
    userCollection(row) {
      getUserCollection(row.id)
        .then((response) => {
          this.collectionList = response.data.data
          this.userCollectionVisible = true
        })
    }
  }
}
</script>
<style >
.cell .el-tag.red{
  color:#ff7777;
      background-color: #f9e2ee;
          border-color: #ff7777;
}
</style>